\subsection{Format string exploit}

It's a popular mistake, to write \TT{printf(string)} instead of \TT{puts(string)} or \TT{printf("\%s", string)}.
If the attacker can put his/her own text into \TT{string}, he/she can crash process,
or get insight into variables in the the local stack.

Take a look at this:

\lstinputlisting[style=customc]{\CURPATH/f.c}

Please note, that \printf has no additional arguments besides single format string.

Now let's imagine, that was the attacker who put \TT{\%s} string into the last \printf first arguments.
I compile this example using GCC 5.4.0 on x86 Ubuntu, and the resulting executable prints \q{world} string if it gets executed!

If I turn optimization on, \printf outputs some garbage, though---probably, strcpy() calls has been optimized and/or
local variables as well.
Also, result will be different for x64 code, different compiler, \ac{OS}, etc.

Now, let's say, attacker could pass the following string to \printf call: \TT{\%x \%x \%x \%x \%x}.
In may case, output is: \q{80485c6 b7751b48 1 0 80485c0} (these are just values from local stack).
You see, there are 1 and 0 values, and some pointers (first is probably pointer to \q{world} string).
So if the attacker passes \TT{\%s \%s \%s \%s \%s} string, the process will crash, because \printf treats 1 and/or 0
as pointer to string, tries to read characters from there and fails.

Even worse, there could be \TT{sprintf (buf, string)} in code, where \TT{buf} is a buffer in the local stack
with size of 1024 bytes or so, attacker can craft \TT{string} in such a way that \TT{buf} will be overflown,
maybe even in a way that would lead to code execution.

Many popular and well-known software was (or even still) vulnerable:

\myindex{Quake}
\myindex{John Carmack}
\begin{framed}
\begin{quotation}
QuakeWorld went up, got to around 4000 users, then the master server exploded.

Disrupter and cohorts are working on more robust code now.

If anyone did it on purpose, how about letting us know... (It wasn't all the people that tried \%s as a name)
\end{quotation}
\end{framed}
( John Carmack's .plan file, 17-Dec-1996\footnote{\url{https://github.com/ESWAT/john-carmack-plan-archive/blob/33ae52fdba46aa0d1abfed6fc7598233748541c0/by_day/johnc_plan_19961217.txt}} )

Nowadays, almost all decent compilers warn about this.

Another problem is the lesser known \TT{\%n} \printf argument: whenever \printf reaches it in a format string, it writes
the number of characters printed so far into the corresponding argument:
\url{http://stackoverflow.com/questions/3401156/what-is-the-use-of-the-n-format-specifier-in-c}.
Thus, an attacker could zap local variables by passing many \TT{\%n} commands in format string.

